import {
	Message,
	Dialog,
	MessageBox
} from 'element-ui';
import {
	Sign
} from '@/libs/sign';
import {
	apiPrefix
} from '@/api/index';
import {
	tansParams
} from "@/libs/victor";
import {
	removeToken,
	removeUserInfo
} from '@/libs/auth'
// 是否显示重新登录
export let isRelogin = {
	show: false
};
const langs = {
	"web-error": {
		"cn": "网络异常",
		"us":"Internet not available"
	},
	"overdue": {
		"cn": "登录状态已过期，您可以继续留在该页面，或者重新登录",
		"us":"Invalid, please sign in"
	},
	"tip": {
		"cn": "系统提示",
		"us":"System reminder"
	},
	"login-repeat": {
		"cn": "重新登录",
		"us":"Sign in"
	},
	"cancel": {
		"cn": "取消",
		"us":"Cancel"
	},
	"power-error": {
		"cn": "权限异常",
		"us":"No access"
	},
	"server-error": {
		"cn": "服务器异常",
		"us":"Server error"
	},
	"not-tally": {
		"cn": "权限异常，当前页面用户与实际登录用户不符，请重新登录",
		"us":"No access, please sign in"
	},
	"request-error": {
		"cn": "请求异常",
		"us":"No permission"
	},
}
export default function({
	store,
	req,
	redirect,
	route,
	app: {
		$axios,
		$cookies
	}
}) {
	// // request拦截器
	$axios.onRequest(config => {
		//强制不传token
		const noToken = (config.headers || {}).isToken === false
		const version = (config.headers || {}).version
		const token = $cookies.get('pchi_token');
		if (token && !noToken) {
			// 让每个请求携带自定义token 请根据实际情况自行修改
			config.headers['pchi_token'] = token;
			console.log(config.url,"token:",token)
		}
		if (version === '' || version === null || version === undefined) {
			//默认版本号为1
			config.headers['version'] = 1;
		}

		const lang = store.state.locale;
		config.headers['lang'] = lang == 'en_US' ? 'en_US' : 'zh_CN';
		// config.headers['lang'] =  'en_US' // 临时配置 2022年07月01日16:50:50
		
		console.log('请求语言 in axios：',config.headers['lang'],config.url)
		// get请求映射params参数
		if (config.method === 'get' && config.params) {
			let url = config.url + '?' + tansParams(config.params);
			url = url.slice(0, -1);
			config.params = {};
			config.url = url;
		}
		//let uri = `${apiPrefix}${config.url}`;
		//uri = uri.split("?")[0];
		// config.headers[`${process.env.config.accessKey}`] = Sign.GET_ACCESS_KEY();
		// config.headers[`${process.env.config.sign}`] = Sign.AES_BASE64_MD5(uri);
		return config;
	});
	let langSelf = store.state.locale == 'en_US' ? 'us' : 'cn';
	let login = `/login`
	let loginEn=`/en/login`
	$axios.onResponse(res => {
		// 未设置状态码则默认成功状态
		const code = res.data.code || 200;
		// 获取错误信息
		const msg = res.data.msg || langs['web-error'][langSelf];
		// 根据返回的code值来做不同的处理(和后端约定)
		switch (code) {
			case 401:
				if (process.client && !isRelogin.show) {
					isRelogin.show = true;
					MessageBox.confirm(langs['overdue'][langSelf], langs['tip'][langSelf], {
						confirmButtonText: langs['login-repeat'][langSelf],
						cancelButtonText: langs['cancel'][langSelf],
						type: 'warning'
					}).then(() => {
						isRelogin.show = false;
						store.dispatch('LogOut').then(() => {
							redirect(langSelf=='cn'?login:loginEn);
						})
					}).catch(() => {
						isRelogin.show = false;
						removeToken()
						removeUserInfo()
					});
					return;
				}
				break;
			case 403:
				// 没有权限
				if (process.client) {
					Message.error(res.data.msg || langs['power-error'][langSelf])
				}
				break;
			case 500:
				// 错误
				if (process.client) {
					Message.error(res.data.msg || langs['server-error'][langSelf])
				}
				break;
			case 700:
				// 错误
				if (process.client) {
					MessageBox.confirm(langs['not-tally'][langSelf], langs['tip'][langSelf], {
						confirmButtonText: langs['login-repeat'][langSelf],
						cancelButtonText: langs['cancel'][langSelf],
						type: 'warning'
					}).then(() => {
						store.dispatch('LogOut').then(() => {
							redirect(langSelf=='cn'?login:loginEn);
						})
					}).catch(() => {});
					return;
				}
				break;
			default:
				return res.data
		}

		return res.data
	});
	$axios.onError(err => {
		if (process.client) {
			Message.error(langs["request-error"][langSelf])
		}
		return Promise.reject(err)
	});
}
